package com.bysc.joinservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bysc.commonutils.Results;
import com.bysc.commonutils.enums.ActivityEnum;
import com.bysc.commonutils.utils.JwtUtils;
import com.bysc.commonutils.vo.CmsActivity;
import com.bysc.joinservice.client.CmsClient;
import com.bysc.joinservice.entity.JoinActivity;
import com.bysc.joinservice.entity.vo.JoinActivityQueryVo;
import com.bysc.joinservice.redis.MessageReceive;
import com.bysc.joinservice.service.JoinActivityService;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.ibatis.ognl.DefaultTypeConverter;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>
 * 报名表 前端控制器
 * </p>
 *
 * @author kkk
 * @since 2024-11-03
 */
@RestController
@Api(tags = "活动报名管理")
@RequestMapping("/joinservice/join-activity")
public class JoinActivityController {

    public static final Map<String, String> status = new ConcurrentHashMap<>();
@Autowired
    private MessageReceive messageReceive;
    @Autowired
    private JoinActivityService joinActivityService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CmsClient cmsClient;
    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 获取当前时间
     *
     * @return
     */
    @GetMapping("/getCurrentTime")
    @ApiOperation(value = "获取当前服务器时间")
    public Results getCurrentTime() {
//        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
        return Results.ok().data("date", new Date(System.currentTimeMillis()));
    }


    /**
     * 获取报名资格
     *
     * @param id      活动id
     * @param str     密文
     * @param request request
     * @return 返回结果
     */
    @PostMapping("/getNumber/{id}/{str}")
    @ApiOperation(value = "获取报名资格")
    public Results getNumber(@ApiParam(name = "id", value = "活动id", required = true) @PathVariable String id, @ApiParam(name = "str", value = "活动id+用户id拼接md5加密后的字符串", required = true) @PathVariable String str, HttpServletRequest request) {
        String userId = JwtUtils.getMemberIdByJwtToken(request);
        joinActivityService.getNumber(str, id, userId);
        return Results.ok();
    }

    /**
     * 根据活动id和token查询报名表
     */
    @PostMapping("/getMyJoinActivity/{id}")
    @ApiOperation(value = "根据活动id和token查询报名表")
    public Results getMyJoinActivity(@ApiParam(name = "id", value = "活动id", required = true) @PathVariable String id, HttpServletRequest request) {
        String userId = JwtUtils.getMemberIdByJwtToken(request);
        JoinActivity joinActivity = joinActivityService.getOne(new QueryWrapper<JoinActivity>().eq("activity_id", id).eq("user_id", userId));
        return Results.ok().data("date", joinActivity);
    }

    /**
     * 新增报名表
     */
    @PostMapping("/addJoinActivity")
    @ApiOperation(value = "新增报名表")
    public Results addJoinActivity(@RequestBody JoinActivity joinActivity, HttpServletRequest request) {
        String userId = JwtUtils.getMemberIdByJwtToken(request);
        String activityId = joinActivity.getActivityId();
        //判断有无报名资格
        Boolean aBoolean = redisTemplate.opsForSet().isMember("activity:join:" + activityId, userId);
        if (!aBoolean) {
            return Results.error().message("未有报名资格");
        }
        boolean save = joinActivityService.save(joinActivity);
        if (save) {
            redisTemplate.opsForSet().add("activity:submit:" + activityId, userId);
            //删除报名资格
            redisTemplate.opsForSet().remove("activity:join:" + activityId, userId);
        }
        return Results.ok().data("date", joinActivity);
    }

    /**
     * 修改报名表
     */
    @ApiOperation(value = "修改报名表")
    @PostMapping("/updateJoinActivity")
    public Results updateJoinActivity(@RequestBody JoinActivity joinActivity, HttpServletRequest request) {
        //获得用户id
        String userId = JwtUtils.getMemberIdByJwtToken(request);
        //只有本人才能修改
        if (!userId.equals(joinActivity.getUserId())) {
            return Results.error().message("无权限修改");
        }
        return Results.ok().data("date", joinActivityService.updateById(joinActivity));
    }


    /**
     * 检查用户与活动之间的状态[已提交/排队中/]
     *
     * @param id 活动id
     * @return 返回结果
     */
    @ApiOperation(value = "检查用户与活动之间的状态")
    @PostMapping("/checkActivityStatus/{id}")
    public Results checkActivityStatus(@PathVariable String id, HttpServletRequest request) {
        //取出用户id
        String userId = JwtUtils.getMemberIdByJwtToken(request);
        return joinActivityService.checkActivityStatus(id, userId);
    }

    /**
     * 分页查询我的报名表
     */
    @ApiOperation(value = "分页查询我的报名表")
    @PostMapping("/getMyJoinActivity/{page}/{limit}")
    public Results getMyJoinActivity(
            @ApiParam(name = "page", value = "当前页码", required = true)
            @PathVariable Integer page,
            @ApiParam(name = "limit", value = "每页记录数", required = true)
            @PathVariable Integer limit,
            HttpServletRequest request
    ) {
        String userId = JwtUtils.getMemberIdByJwtToken(request);
        Page page1 = new Page(page, limit);
        IPage page2 = joinActivityService.page(page1, new QueryWrapper<JoinActivity>().eq("user_id", userId));
        
        return Results.ok().data("list", page2);
    }

    @GetMapping("/export/{id}")
    @ApiOperation(value = "导出报名表")
    public void export(HttpServletResponse response, @PathVariable String id) {
        joinActivityService.exportData(response, id);
    }


    @ApiOperation(value = "根据用户token分页查询报名表和活动信息")
    @PostMapping("/getMyJoinActivityAndActivity/{page}/{limit}")
    public Results getMyJoinActivityAndActivity(@ApiParam(name = "page", value = "当前页码", required = true)
                                                @PathVariable Integer page,
                                                @ApiParam(name = "limit", value = "每页记录数", required = true)
                                                @PathVariable Integer limit, HttpServletRequest request) {
        String userId = JwtUtils.getMemberIdByJwtToken(request);

        IPage<JoinActivity> joinActivityPage = new Page<>(page, limit);
        LambdaQueryWrapper<JoinActivity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(JoinActivity::getUserId, userId);
        // 执行分页查询
        joinActivityPage = joinActivityService.page(joinActivityPage, wrapper);
        // 创建目标分页对象
        IPage<JoinActivityQueryVo> resultPage = new Page<>(page, limit);
        List<JoinActivityQueryVo> list = new ArrayList<>();
        for (JoinActivity joinActivity :  joinActivityPage.getRecords()) {
            JoinActivityQueryVo joinActivityQueryVo = new JoinActivityQueryVo();
            Object object = cmsClient.queryActivityById(joinActivity.getActivityId()).getData().get("activity");
            BeanUtils.copyProperties(joinActivity, joinActivityQueryVo);
            if (object instanceof Map) {
                // 使用 ObjectMapper 将 Map 转换为 CmsActivity
                CmsActivity cmsActivity = objectMapper.convertValue(object, CmsActivity.class);
                BeanUtils.copyProperties(cmsActivity, joinActivityQueryVo);
            }
            joinActivityQueryVo.setStatusName(ActivityEnum.getValueById(joinActivityQueryVo.getStatus()));
            list.add(joinActivityQueryVo);
        }
        // 设置分页结果
        resultPage.setRecords(list);
        resultPage.setTotal(joinActivityPage.getTotal());
        resultPage.setSize(joinActivityPage.getSize());
        resultPage.setCurrent(joinActivityPage.getCurrent());
        return Results.ok().data( "JoinActivityAndActivityByPage", resultPage);
    }
    //手动初始化活动
    /*
    *
   SELECT *
FROM `cms_activity`
WHERE
    DATE_FORMAT(NOW(), '%Y-%m-%d %H:%i:%s') BETWEEN join_start AND join_end
    AND STATUS = 1 AND is_deleted = 0;
    * */
    @PostMapping("/initActivity/{id}")
    @ApiOperation(value = "手动初始化活动")
    public Results initActivity(@ApiParam(name = "id", value = "活动id:状态码，1-可用，0不可用，-1-删除", required = true)@PathVariable String id) {
        messageReceive.receiveMessage(id);
        return Results.ok();
    }
}

